package com.menggudf.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.menggudf.constant.Constants;
import com.menggudf.http.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

//@WebFilter(urlPatterns = "/*")
@Slf4j
@Deprecated
public class RequestFilter implements Filter {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        /*if (this.sysLogInfoMapper == null) {
            this.sysLogInfoMapper = SpringUtils.getBean("sysLogInfoMapper");
        }
        if(this.stringRedisTemplate ==null){
            this.stringRedisTemplate =  SpringUtils.getBean("stringRedisTemplate");
        }*/
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        //保存系统日志
        //SysLogInfo sysLogInfo = new SysLogInfo();
        Long requestId = System.currentTimeMillis();
        String mBody = ((RequestWrapper) servletRequest).mBody;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String getParamer = JSON.toJSONString(request.getParameterMap());
        String authorization = request.getHeader("authorization");
        if(Objects.nonNull(authorization)){
            ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
            String token = authorization.replace("Bearer", "").trim();
            String key = Constants.TOKEN_USER_INFO_CACHE_PREFIX + token;
            String tokenObj = valueOperations.get(key);
            //SysUserDetailsVo javaObject = JSONObject.toJavaObject(JSON.parseObject(tokenObj), SysUserDetailsVo.class);
            //sysLogInfo.setCreator(javaObject.getUsername());
        }
        MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);

        //添加header
        mutableRequest.putHeader("key", "apitest");
        mutableRequest.putHeader("password", "test123456");
        log.info("[Api Access] start. id: {}, uri: {}, method: {}, client: {}", requestId,
                request.getRequestURI(), request.getMethod(), getIP(request));
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        ContentCachingResponseWrapper wrapResponse = new ContentCachingResponseWrapper(response);
        filterChain.doFilter(mutableRequest, servletResponse);

        // 获取接口响应报文
        String resMsg = "";
        byte[] data = wrapResponse.getContentAsByteArray();
        String responseBody = new String(data, StandardCharsets.UTF_8);
        log.info("原始返回数据： " + responseBody);

        long end = System.currentTimeMillis();
        long costTime = end - start;
        log.info("[Api Access]  end. id: {}, duration: {} ms", requestId,
                end - start);


        //sysLogInfo.setCreateTime(new Date());
        //sysLogInfo.setCostTime(costTime);
        //sysLogInfo.setIp(getIP(request));
        //sysLogInfo.setParameter("POST".equals(request.getMethod()) ? mBody : getParamer);
        //sysLogInfo.setReqUrl(((HttpServletRequest) servletRequest).getRequestURI());
        //sysLogInfo.setResoposeContent(resMsg.length()>65535?resMsg.substring(0,655354):resMsg);
        //sysLogInfo.setMethod(request.getMethod());
        //boolean issuccess = this.sysLogInfoMapper.insert(sysLogInfo) > 0;
        //log.info("新增系统日志是否成功：{}", issuccess);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }


    private String getWeightMessage(HttpServletRequest httpRequest) throws Exception {
        String messageText = HttpURLConnectionUtils.getResult(httpRequest.getInputStream(), "UTF-8");
        Map<String, Object> params = new HashMap<String, Object>();
        StringBuffer msg = new StringBuffer("获取称重传递参数:");
        //外部接口调用日志
        try {
            if (StringUtils.isEmpty(messageText)) {
                Enumeration parameterNames = httpRequest.getParameterNames();
                while (parameterNames.hasMoreElements()) {
                    String name = String.valueOf(parameterNames.nextElement());
                    String parameter = httpRequest.getParameter(name);
                    msg.append(name + "=" + parameter + "&");
                }
                log.debug(String.valueOf(msg));
                String sendcode = httpRequest.getParameter("/sendcode");
                double weight = Double.valueOf(httpRequest.getParameter("weight"));
                double length = Double.valueOf(httpRequest.getParameter("length"));
                double width = Double.valueOf(httpRequest.getParameter("width"));
                double height = Double.valueOf(httpRequest.getParameter("height"));
                String machine = httpRequest.getParameter("machine");
                if (StringUtils.isEmpty(sendcode)) {
                    log.error("执行【getWeightMessage】获取转单号错误");
                    throw new Exception("参数错误");
                }
                params.put("sendcode", sendcode);
                params.put("weight", weight);
                params.put("length", length);
                params.put("width", width);
                params.put("height", height);
                params.put("machine", machine);
            } else {
                log.debug("直接传输数据：\n" + messageText);
                msg.append(messageText);
                log.debug(String.valueOf(msg));
                JSON.toJSONString(messageText);
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
            throw new Exception("参数错误");
        }
        return StringUtils.isEmpty(messageText) ? JSON.toJSONString(params) : messageText;
    }


    /**
     * 获取IP地址
     *
     * @param request 请求
     * @return request发起客户端的IP地址
     */
    private String getIP(HttpServletRequest request) {
        if (request == null) {
            return "0.0.0.0";
        }

        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");

        String UNKNOWN_IP = "unknown";
        if (StringUtils.isNotEmpty(XFor) && !UNKNOWN_IP.equalsIgnoreCase(XFor)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if (index != -1) {
                return XFor.substring(0, index);
            } else {
                return XFor;
            }
        }

        XFor = Xip;
        if (StringUtils.isNotEmpty(XFor) && !UNKNOWN_IP.equalsIgnoreCase(XFor)) {
            return XFor;
        }

        if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }
}
